import { post } from "./axiosUtils";

/**
 * 流式请求方法
 * @param {String} url 请求的URL
 * @param {Object} data 请求数据
 * @param {AbortController} abortController 可选的AbortController实例
 * @param {Function} onData 处理数据流的回调函数
 * @param {Function} onComplete 请求完成时的回调函数
 * @param {Function} onError 错误处理回调函数
 */
export function streamPost(
  url: string,
  data: any,
  abortController?: AbortController,
  onData?: (chunk: string) => void,
  onComplete?: () => void,
  onError?: (error: any) => void
): Promise<void> {
  const controller = abortController || new AbortController();

  return fetch(`${getBaseURL()}${url.startsWith("/") ? "" : "/"}${url}`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Accept: "text/event-stream",
      Connection: "keep-alive",
    },
    body: JSON.stringify(data),
    signal: controller.signal,
  })
    .then((response) => {
      if (!response.ok || !response.body) {
        throw new Error(`HTTP ${response.status}`);
      }

      return response.body.getReader();
    })
    .then((reader) => {
      const decoder = new TextDecoder("utf-8");

      function read(): Promise<void> {
        return reader
          .read()
          .then(({ done, value }) => {
            if (done) {
              onComplete && onComplete();
              return;
            }

            const chunk = decoder.decode(value, { stream: true });
            onData && onData(chunk);

            return read();
          })
          .catch((error) => {
            onError && onError(error);
            throw error;
          });
      }

      return read();
    })
    .catch((error) => {
      onError && onError(error);
      throw error;
    });
}

/**
 * 获取表格数据的专用方法
 * @param {String} sessionId 会话ID
 */
export function getTableData(sessionId: string) {
  return post("/json_res", { session_id: sessionId }).then((response: any) => {
    return response.data || response; // 兼容不同的响应结构
  });
}

/**
 * 获取基础URL（与axiosUtils保持一致）
 */
function getBaseURL(): string {
  let baseURL = "";

  if (process.env.NODE_ENV == "development") {
    baseURL = "/api";
  } else if (process.env.NODE_ENV == "debug") {
    baseURL = "";
  } else if (process.env.NODE_ENV == "production") {
    baseURL = "http://192.168.10.10:8091";
  }

  return baseURL;
}

// 导出对象
export default {
  streamPost,
  getTableData,
};
